<template>
  <n-form ref="formRef" :model="loginValue" :rules="rules" :show-label="false">
    <n-form-item path="username">
      <n-input v-model:value="loginValue.username" placeholder="输入账号" >
        <template #prefix>
          <Icon src="self-login-user" />
        </template>
      </n-input>
    </n-form-item>
    <n-form-item path="password">
      <n-input
        v-model:value="loginValue.password"
        type="password"
        show-password-on="click"
        placeholder="输入密码"
        ><template #prefix>
          <Icon src="self-login-password" />
        </template>
      </n-input>
    </n-form-item>
    <n-form-item v-if="isRememberMeShow" path="rememberMe">
      <n-radio :checked="rememberMe" @click="rememberMe = !rememberMe"> 记住我 </n-radio>
    </n-form-item>
    <component :is="slotFormComponent" v-if="slotFormComponent"></component>
    <n-form-item>
      <n-button attr-type="submit" type="primary" :block="true" :loading="btnLoading" @click="handleValidateClick">
        登录
      </n-button>
    </n-form-item>
  </n-form>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, defineAsyncComponent } from 'vue'
  import { useNotification, FormInst } from 'naive-ui'
  import { udpUserStore } from 'udp/store/user-store'
  import { useRouter } from 'vue-router'
  import Icon from 'udp/components/tools/icon'
  import plugin from '@/config/plugin'
  import * as config from '@/config/theme-overrides'
  const slotModule = import.meta.glob('../../../src/components/layout-tools/**.vue')
  const slotForm = '../../../src/components/layout-tools/slot-login-form.vue'

  export default defineComponent({
    name: 'LoginForm',
    components: { Icon },
    setup() {
      const UserStore = udpUserStore()
      const formRef = ref<FormInst | null>(null)
      let slotFormComponent = null
      if (slotModule[slotForm]) {
        slotFormComponent = defineAsyncComponent(slotModule[slotForm])
      }
      const rememberMe = ref(UserStore.getRememberMe())
      const isRememberMeShow = ref(config.isRememberMeShow)
      // eslint-disable-next-line no-undef
      const modelRef = reactive<AuthApi.loginType>({
        username: null,
        password: null
      })
      const btnLoading = ref(false)
      const notification = useNotification()
      const router = useRouter()
      const rules = {
        username: [
          {
            required: true,
            trigger: 'blur', 
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            trigger: 'blur', 
            message: '请输入密码'
          }
        ]
      }
      return {
        slotFormComponent,
        rememberMe,
        isRememberMeShow,
        formRef,
        loginValue: modelRef,
        rules,
        btnLoading,
        handleValidateClick(e: MouseEvent) {
          e.preventDefault()
          formRef.value?.validate(errors => {
            if (!errors) {
              btnLoading.value = true
              UserStore.loginHandle({
                username: modelRef.username,
                password: modelRef.password,
                scope: 'openid',
                grant_type: 'password'
              })
                .then(() => {
                  const redirect = UserStore.getCurrentRedirectUrl()
                  const { loginSuccessfulCallback } = plugin
                  loginSuccessfulCallback && loginSuccessfulCallback()
                  UserStore.setRememberMe(isRememberMeShow.value ? rememberMe.value : false)
                  if (redirect.startsWith('http')) {
                    window.location.href = redirect
                  } else {
                    router.push(redirect)
                  }
                })
                .catch(error => {
                  const errorCode = error.response?.status
                  notification.error({
                    content:
                      errorCode === 401
                        ? '用户名或密码错误，请修改后重新登录！'
                        : error.response?.data.error_description || '登录失败，请重试！',
                    duration: 2000
                  })
                })
                .finally(() => {
                  btnLoading.value = false
                })
            }
          })
        }
      }
    }
  })
</script>

<style lang="less" scoped></style>
